package orm

import (
	"gin_web/orm/db_core"
	"gin_web/orm/models"
	log "gin_web/piugins/logger"
	"gorm.io/gorm"
)

var db *gorm.DB

func init() {
	db = db_core.InitDB()
}

func Migrate() {
	// 多次运行并不会影响到原数据
	err := db.AutoMigrate(
		// 加入自己写的models
		models.Book{},
		models.Category{},

		models.TradeMode{},
	)
	if err != nil {
		panic(err)
	}
}

func Insert(model interface{}) bool {
	// use demo
	// tmpModel := models.Book{
	// 	Title:       "test",
	// 	Author:      "test",
	// 	ISBN:        "1234567890",
	// 	Pages:       100,
	// 	Price:       89.00,
	// 	Description: "test",
	// 	CategoryID:  1,
	// }
	// Insert(&tmpModel)
	commitResult := db.Create(model)
	if commitResult.Error != nil {
		log.Info.Println(commitResult.Error)
		return false
	}
	return true
}

func Update(model interface{}) {
	// db.Model(&model).Update("Price", 200)
}

func Delete(model interface{}, id int) {
	// db.Delete(model, id)
}

func FindByID(model interface{}, id int) {
	// return db.First(&model, id) // find product with integer primary key
}

func FindByValue(model interface{}, value interface{}) {
	// db.First(model, "code = ?", "D42") // find product with code D42
}

func Test() {

}
